// pages/my/index/index.js

const app = getApp();
const util = require('../../../utils/util');
const common = require('../../../utils/common');
const api = require("../../../config/api");
const requestUtil = require("../../../utils/request");
const timConst = require("../../../config/const");
import QRCode from '../../../utils/weapp-qrcode.js'

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		CustomBar: app.globalData.CustomBar,
		cardInfo: {},
		userType: 2,
		hasCardInfo: false, // 是否有卡片信息
		hasGetPhoneNumber: false, // 是否已获取手机号
		visitedNum: 0, // 访问量
		todayVisitedNum: 0, // 今日访问量
		reInitToGetPhone: true, // 重置获取手机号
		fyNum: 1, // 页码
		fySize: 10, // 每页展示数
		historyList: [],
		firstTimeInIndex: true,
		// 电子名片信息
		bcd_info:{},
		// 产品信息
		cp_info:[],
		model_wx:"none",
		bcd_id_show:undefined,
		image_url:api.url+"/profile/upload/2024/06/23/电子名片背景图_20240623113649A001.jpg"
	},
	onShow() {
		console.log("与纳新了");
		let token=wx.getStorageSync("token")
		if(token){
			// 通过token查找手机号
			this.getphone_token(token)
		}else{
			wx.showToast({
				title:"请登录",
				icon:"none"
			})
		}
	},
	onLoad: function(res) {
		if(res.bcd_id!=undefined && res.bcd_id && wx.getStorageSync("token")){
			this.setData({
				bcd_id_show:res.bcd_id
			})
			let data=wx.getStorageSync("info")
			if(wx.getStorageSync("info").bcId){
				 data=wx.getStorageSync("info")
				data.bcId=res.bcd_id
			}else{
				 data={bcId:res.bcd_id}
			}
			wx.setStorageSync("info",data)
		}
	},
	 processAndDisplayFiles: function (files) {
	    // 处理函数，提取文件名
	    return {
			path:files.replace(/^http:\/\/localhost/, api.url),
			name:files.split('/').pop().split("_")[0],
				type:files.split('/').pop().split(".")[1]
				};
	  },
	// 查询公司产品
	select_cpId(){
		requestUtil.request("POST","/pdt_sql/select_cpId",{
			cpId:this.data.bcd_info.pcId,
		}).then((res)=>{
			if(res.data.status==200){
				this.setData({
					cp_info:res.data.data
				})
			}
			console.log(res.data,"公司产品嘻嘻你");
		})
	},
	user_bcd_bangding(){
		requestUtil.request("POST","/bcd_api/user_bcd_bangding",{
			bcd_id:wx.getStorageSync("info").bcId,
			user_id:wx.getStorageSync("info").userId
		}).then((res)=>{
			this.select_cpId()
		})
	},
	tongxun(){
		wx.addPhoneContact({
		  firstName: this.data.bcd_info.bcUserName, // 名
		  lastName: this.data.bcd_info.bcUserName.split('')[0], // 姓
		  mobilePhoneNumber: this.data.bcd_info.bcUserPhone, // 手机号码
		  organization: this.data.bcd_info.bcName, // 公司名称
		  title: this.data.bcd_info.bcPosition, // 职位
		  success: function (res) {
		    console.log('添加联系人成功');
		  },
		  fail: function (err) {
		    console.log('添加联系人失败', err);
		  }
		});
	},
	dadianhua(){
		wx.makePhoneCall({
		  phoneNumber: this.data.bcd_info.bcUserPhone //仅为示例，并非真实的电话号码
		})
	},
	getphone_token(token){
		requestUtil.request("POST","/sql_api/getphone_token",{
			token:token,
		}).then((res)=>{
			if(res.data.status==200){
				this.setData({
					hasGetPhoneNumber:res.data.data.userPhone?res.data.data.userPhone:''
				})
				this.login_user()
			}else{
				wx.showToast({
					title:"请手动登录",
					icon:"error"
				})
				this.setData({
				CustomBar: app.globalData.CustomBar,
				cardInfo: {},
				userType: 2,
				hasCardInfo: false, // 是否有卡片信息
				hasGetPhoneNumber: false, // 是否已获取手机号
				visitedNum: 0, // 访问量
				todayVisitedNum: 0, // 今日访问量
				reInitToGetPhone: true, // 重置获取手机号
				hasNoMoreHistory: false, // 没有更多记录
				hasHistoryList: false, // 判断是否有历史记录
				fySize: 10, // 每页展示数
				historyList: [],
				firstTimeInIndex: true,
				// 电子名片信息
				bcd_info:{},
				// 产品信息
				cp_info:[],
				model_wx:"none",
				bcd_id_show:undefined
				})
			}
		})
	},

	onShareAppMessage: function(o) {
		let _this = this;
		if (o.from) {
			return {
				title: "您好，这是我的名片。", //转发的标题
				path: '/pages/my/index/index?bcd_id=' + wx.getStorageInfo("info").bcId
			};
		}
	},

	/**
	 * 添加当前员工到腾讯云平台【员工限定，顾客有别的方法】
	 */
	addUser: async function() {
		if (app.globalData.userType == 2) {
			return;
		}
		if (app.globalData.adminSig == null) {
			return;
		}
		if (util.objIsNull(app.globalData.employeeInfo)) {
			return;
		}
		let random = parseInt(Math.random() * 10000);
		let url = 'https://console.tim.qq.com/v4/im_open_login_svc/account_import' + '?sdkappid=' + timConst
			.TimOptions.SDKAppID + '&identifier=admin' + '&usersig=' + app.globalData.adminSig +
			'&random=' + random + '&contenttype=json';
		let data;
		if (app.globalData.employeeInfo.headImgUrl) {
			data = {
				Identifier: 'E' + app.globalData.employeeInfo.id.toString(),
				Nick: app.globalData.employeeInfo.name,
				FaceUrl: app.globalData.employeeInfo.headImgUrl
			}
		} else {
			data = {
				Identifier: 'E' + app.globalData.employeeInfo.id.toString(),
				Nick: app.globalData.employeeInfo.name
			}
		}
		let res = await requestUtil.request("POST", url, data);
		if (res.data.ActionStatus == 'FAIL') {
			console.error('添加用户失败，ErrorCode：' + res.data.ErrorCode);
			console.error('ErrorInfo：' + res.data.ErrorInfo);
		} else {
			console.log('----------添加单个用户')
		}
	},

	/**
	 * 跳转到编辑名片页面
	 */
	toModify: function(e) {
		this.setData({
			model_wx:"show"
		})
	},
	copy_wx(){
		if (!this.data.bcd_info.bcWxNumber) {
			util.showToast('暂无微信号');
			return;
		}
		wx.setClipboardData({
		      data: this.data.bcd_info.bcWxNumber,
		      success: function(res) {
		        wx.showToast({
		          title: '复制成功',
		          icon: 'success',
		          duration: 2000
		        });
		      },
		      fail: function() {
		        wx.showToast({
		          title: '复制失败',
		          icon: 'none',
		          duration: 2000
		        });
		      }
		    });
			this.setData({
				model_wx:"none"
			})
	},
	model_wx(){
		this.setData({
			model_wx:"none"
		})
	},
	/**
	 * 跳转到我的名片页面
	 */
	toMyCard: function() {
		if (!this.data.bcd_info.bcMailbox) {
			util.showToast('暂无邮箱');
			return;
		}
		wx.setClipboardData({
		      data: this.data.bcd_info.bcMailbox,
		      success: function(res) {
		        wx.showToast({
		          title: '复制成功',
		          icon: 'success',
		          duration: 2000
		        });
		      },
		      fail: function() {
		        wx.showToast({
		          title: '复制失败',
		          icon: 'none',
		          duration: 2000
		        });
		      }
		    });
	},

	/**
	 * 历史记录
	 */
	toHistory: function() {
		wx.navigateTo({
			url: '../../my/history/list'
		})
	},

	/**
	 * 谁看过我
	 */
	toWhoSeenMe: function(e) {
		console.log(e,"eeeeeeeeeeee");
		// let type = e.currentTarget.dataset.type;
		// wx.navigateTo({
		// 	url: '../../my/who-seen-me/seen?type=' + type
		// })
	},

	/**
	 * 去聊天室
	 */
	toChatRoom: function() {
		wx.navigateTo({
			url: '../../card-center/loginpage/login?userType=1',
		})
	},
	toQuestion: function() {
		wx.navigateTo({
			url:"../map/map?x_type="+this.data.bcd_info.bcXCoordinate+"&y_type="+this.data.bcd_info.bcYCoordinate+"&name_type="+this.data.bcd_info.bcAddress,
		})
	},
	/**
	 * 创建名片
	 */
	createCard: function() {
		wx.navigateTo({
			url: '../../card-create-modify/card-cm?type=1'
		})
	},

	/**
	 * 修改头像
	 */
	toChangeAvatar: function() {
		wx.navigateTo({
			url: '/pages/my/avatar-modify/avatar',
		})
	},

	/**
	 * 获取被访问量
	 */
	getVisitedNum: async function() {
		let res = await requestUtil.request("POST", api.urls.getHistoryTotal, {
			userId: this.data.cardInfo.id
		})
		if (res.data.code != 0) {
			util.showToast(res.data.msg, 'none');
			return;
		}
		let visitedList = res.data.data;
		for (let i in visitedList) {
			visitedList[i].totalTypeName = common.formatVisitType(visitedList[i].totalType);
		}
		this.setData({
			visitedList: visitedList,
		})
	},

	/**
	 * 修改缓存
	 */
	changeTempHistoryList: function(list) {
		if (list && list.length > 0) {
			wx.setStorageSync('userIds', list.toString());
		}
	},

	/**
	 * 显示获取手机modal
	 */
	showModal: function() {
		this.setData({
			modalName: 'GetPhoneModal'
		});
	},

	/**
	 * 拒绝获取手机
	 */
	rejectModal: function() {
		this.setData({
			cardInfo: {},
			reInitToGetPhone: true,
			hasCardInfo: false,
			hasGetPhoneNumber: false,
		});
		app.globalData.hasGetPhoneNumber = false
		this.hideModal();
	},
	card_add_wxml(){
		// 先跳转到 公司页面  传递 info
		let info_storge=wx.getStorageSync('info')
		console.log(info_storge,"info");
		wx.navigateTo({
			url:"../../my/cpt_info/cpt_info?userId="+info_storge.userId+"&userPhone="+info_storge.userPhone
		})
	},
	/**
	 * 隐藏modal
	 */
	hideModal: function() {
		this.setData({
			modalName: ''
		});
	},

	/**
	 * 获取用户手机号 sql
	 */
	getPhoneNumber(e) {
		let even=e
		let code = ""
		wx.login({
			success: (res) => {
				const encryptedData = even.detail.encryptedData;
				const iv = even.detail.iv;
				code = res.code
				this.getphone(code, iv, encryptedData)

			}
		})
	},
	// sql
	getphone(code, iv, encryptedData) {
		// 获取 access_token 获取手机号
		requestUtil.request("POST", "/sql_api/get_AccessToken", {
			"appid": api.appid,
			"secret": api.accessKeySecret,
			"grant_type": "client_credential",
			"code": code,
			"iv":iv,
			"encryptedData":encryptedData
		}).then((res)=>{
			this.setData({
				modalName: ''
			})
			// 查询电子名片
			// 手机号res.data.data.phoneNumber
			this.setData({
				hasGetPhoneNumber:res.data.data.phoneNumber,
			})
			this.login_user()
		})
	},
	 canParseAsJson(jsonString) {
	    try {
	        JSON.parse(jsonString);
	        return true; // 如果没有抛出异常，说明可以被解析为JSON
	    } catch (e) {
	        return false; // 如果抛出异常，说明不是有效的JSON
	    }
	},
	// 登录获取用户信息sql
	login_user(){
		let bcd_id=wx.getStorageSync('info')
		requestUtil.request("POST","/sql_api/login",{
			"phone":this.data.hasGetPhoneNumber,
			"bcd_id":bcd_id.bcId?bcd_id.bcId:"",
			"userId":bcd_id.userId
		}).then((res)=>{
			console.log(res,'res');
			if(res.data.status==200){
				let token=res.data.data.token
				wx.setStorageSync("token",token)
				let info={userId:res.data.data.user[0].userId,userPhone:res.data.data.user[0].userPhone,pcId:res.data.data.bcd==null?"":res.data.data.bcd[0].pcId,bcId:res.data.data.bcd==null?"":res.data.data.bcd[0].bcId}
				console.log(info,"info");
				if(res.data.data.bcd!=null&&res.data.data.bcd.length!=0){
					this.setData({
						hasCardInfo:true,
						userType:1
					})
				}
				wx.setStorageSync("info",info) 
				if(res.data.data.bcd!=null){
					this.canParseAsJson(res.data.data.bcd[0].bcFile)?res.data.data.bcd[0].bcFile=JSON.parse(res.data.data.bcd[0].bcFile):res.data.data.bcd[0].bcFile
					this.canParseAsJson(res.data.data.bcd[0].bcImgList)?res.data.data.bcd[0].bcImgList=JSON.parse(res.data.data.bcd[0].bcImgList):res.data.data.bcd[0].bcImgList
					this.canParseAsJson(res.data.data.bcd[0].pcSpeech)?res.data.data.bcd[0].pcSpeech=JSON.parse(res.data.data.bcd[0].pcSpeech):res.data.data.bcd[0].pcSpeech
					this.canParseAsJson(res.data.data.bcd[0].bcWxImg)?res.data.data.bcd[0].bcWxImg=JSON.parse(res.data.data.bcd[0].bcWxImg):res.data.data.bcd[0].bcWxImg
					this.canParseAsJson(res.data.data.bcd[0].bcUserImg)?res.data.data.bcd[0].bcUserImg=JSON.parse(res.data.data.bcd[0].bcUserImg):res.data.data.bcd[0].bcUserImg
					this.canParseAsJson(res.data.data.bcd[0].pcProgramCode)?res.data.data.bcd[0].pcProgramCode=JSON.parse(res.data.data.bcd[0].pcProgramCode):res.data.data.bcd[0].pcProgramCode
					if(res.data.data.bcd[0].bcFile.length!=0 && typeof res.data.data.bcd[0].bcFile!="string"){
						for (var i = 0; i < res.data.data.bcd[0].bcFile.length; i++) {
							res.data.data.bcd[0].bcFile[i]= {path:this.processAndDisplayFiles(res.data.data.bcd[0].bcFile[i]).path,name:this.processAndDisplayFiles(res.data.data.bcd[0].bcFile[i]).name,type:this.processAndDisplayFiles(res.data.data.bcd[0].bcFile[i]).type}
						}
					}else if(typeof res.data.data.bcd[0].bcFile =="string"){
						res.data.data.bcd[0].bcFile=[{path:this.processAndDisplayFiles(res.data.data.bcd[0].bcFile).path,name:this.processAndDisplayFiles(res.data.data.bcd[0].bcFile).name,type:this.processAndDisplayFiles(res.data.data.bcd[0].bcFile).type}]
					}
					this.setData({
						bcd_info:res.data.data.bcd[0]
					})
					this.user_bcd_bangding()
				}
			}
		})
	},
	add_my(){
		wx.navigateTo({
			url:"../addmy/addmy?bcId="+this.data.bcd_info.bcId
		})
	},
	getwendang(e){
		wx.showLoading()
		let _this=this
		let path=e.target.dataset.type.path
		console.log(e,"eeeeeeeeeeeeeeeeeee");
		wx.downloadFile({
		  url: path,
		  success: function (res) {
		    wx.hideLoading();
		    const filePath = res.tempFilePath;
		    wx.openDocument({
		      filePath: filePath,
		      success: function (res) {
		        console.log('打开文档成功');
		      },
		      fail: function (err) {
		        console.error('打开文档失败', err);
		      }
		    });
		  },
		  fail: function (err) {
		    wx.hideLoading();
		    console.error('下载文件失败', err);
		  }
		});

	},
	/**
	 * 获取手机号
	 */
	getPhone: async function(params) {
		let _this = this;
		let res = await requestUtil.request("POST", api.urls.getPhone, params);
		if (!res.data) {
			wx.showToast({
				title: '无法获取信息，请重试。',
				icon: 'none'
			})
			_this.setData({
				reInitToGetPhone: false,
			})
			return;
		}
		let phone = res.data.purePhoneNumber; // 没有区号的手机号
		this.bindUser(phone);
	},

	/**
	 * openid绑定用户
	 */
	bindUser: async function(phone) {
		let openid = wx.getStorageSync('openid');
		if (!openid) {
			this.reLogin(phone, "bindUser");
			return;
		}
		let params = {
			xcxOpenid: openid,
			mobile: phone
		}
		let bindRes = await requestUtil.request("POST", api.urls.bindEmployee, params);
		if (bindRes.data.code != 0) {
			util.showToast(bindRes.data.msg, 'none');
			return;
		}
		util.showToast('绑定成功', 'success');
		app.globalData.phone = phone;
		app.onShow();
		this.onShow();
		this.hideModal();
	},

	/**
	 * login重新获取session_key
	 */
	reLogin: function(params, type) {
		let _this = this;
		console.log(res.code);
		wx.login({
			success: async function(res) {
				let init = await requestUtil.request("POST", api.urls.initUserInfo, {
					code: res.code
				});
				wx.setStorage({
					key: 'openid',
					data: init.data.data.openid
				});
				wx.setStorage({
					key: "session_key",
					data: init.data.data.session_key
				});
				if (type == "getPhone") {
					params.sessionkey = init.data.data.session_key;
					_this.getPhone(params);
				} else if (type == "bindUser") {
					_this.bindUser(params);
				}
			}
		})
	},

	/**
	 * 点击查看更多
	 */
	moreDetail: function(e) {
		let id = e.currentTarget.dataset.id;
		// 固定，历史记录页面，顾客可查看员工信息
		wx.navigateTo({
			url: '../../card/card?id=' + id + '&type=' + 1,
		})
	},
	toMyCustomer: function() {
		wx.navigateTo({
			url: '../../my/my-customer/my-customer',
		})
	},
	showModal2(e) {
		this.setData({
			modalName: e.currentTarget.dataset.target
		})
	},
	hideModal(e) {
		this.setData({
			modalName: null
		})
	},
	getEwm(api) {
		new QRCode('myQrcode', {
			text: api,
			width: 160,
			height: 160,
			colorDark: '#2196F3',
			colorLight: '#ffffff',
			correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
			callback: (res) => {
				console.log(res.path)
			}
		})
	},

})